﻿/// <reference path="Events.js" />


function EventType()
{
	this.Handlers = new Array();
}
EventType.prototype.Handlers = null;

function EventSender()
{
	this.Events = new Object();
}
EventSender.prototype.Events = null;
EventSender.prototype.addEventListener = function addEventListener(type, fn)
{
	if (type == "" || type == null)
		Throw("Event type can't be null or empty string.");
	if (fn == null || (typeof (fn) != "function" && typeof (fn) != "string"))
		Throw("Event handler can't be null and has to be a function or name of a function.");

	type = type.toLowerCase();
	if (this.Events[type] == null)
	{
		this.Events[type] = new EventType();
	}

	this.Events[type].Handlers.push(fn);
}
EventSender.prototype.removeEventListener = function removeEventListener(type, fn)
{
	if (type == "" || type == null)
		Throw("Event type can't be null or empty string.");
	if (fn == null || typeof (fn) != "function")
		Throw("Event handler can't be null and has to be a function.");

	type = type.toLowerCase();
	if (this.Events[type] == null)
	{
		this.Events[type] = new EventType();
	}

	var h = this.Events[type].Handlers, hl = h.length;

	for (var iHandler = 0; iHandler < hl; ++iHandler)
	{
		if (h[iHandler] == fn)
		{
			h.splice(iHandler, 1);
			break;
		}
	}
}
EventSender.prototype.AddEvent = Events._AddEventObject;
EventSender.prototype.RemoveEvent = Events._RemoveEventObject;
EventSender.prototype.RaiseEvent = function RaiseEvent(type, args)
{
	if (type == "" || type == null)
		Throw("Event type can't be null or empty string.");

	type = type.toLowerCase();
	if (this.Events[type] == null) return;

	if (args == null) args = new Object();

	args.currentTarget = this;
	args.target = this;

	for (var i = 0; i < this.Events[type].Handlers.length; ++i)
		this.Events[type].Handlers[i](args);
}
EventSender.prototype.IsHandled = function IsHandled(type)
{
	type = type.toLowerCase();
	return this.Events[type] != null && this.Events[type].Handlers.length > 0;
}
EventSender.prototype.ClearHandlers = function ClearHandlers(type)
{
	if (type == "" || type == null)
		Throw("Event type can't be null or empty string.");

	type = type.toLowerCase();
	this.Events[type].Handlers.length = 0;
}
